﻿/*
位数和排序 
Time Limit:1000MS  Memory Limit:32768K

  
Description:
将每组整数按各位数字和的大小进行排序输出。
数字和排序是指，如果两个整数的数字和不相等，则数字和大者排在前，若数字和相等，则整数值大者排在前。

Input:
输入一些整数组，第一个数N表示该数组有N个数，随后输入N个整数（0<N<=999）。若N为0，则程序运行结束。 
Output:
按所给的比较方法从大到小的顺序输出N个整数，每个数之间用一个空格隔开，行末无空格。 
Sample Input:
5
35 27 88 61 23
8
11 45 54 31 24 76 999 1000
0
Sample Output:
88 27 35 61 23
999 76 54 45 24 31 11 1000
*/

#include <algorithm>
#include <vector>
#include <iostream>

using namespace std;

class NumberInfo
{
private:
	int value;
	int sum;
public:
	NumberInfo(int value_=0):
		value(value_), sum(0)
		{

		}
	void calSum()
	{
		int temp=this->value;
		this->sum=0;
		while (temp)
		{
			this->sum+=temp%10;
			temp/=10;
		}
	}
	friend istream& operator>> (istream& is, NumberInfo& numberInfo)
	{
		is>>numberInfo.value;
		numberInfo.calSum();
		return is;
	}
	friend ostream& operator<< (ostream& os, const NumberInfo& numberInfo)
	{
		os<<numberInfo.value;
		return os;
	}
	friend bool compare(const NumberInfo& ni1, const NumberInfo& ni2)
	{
		if(ni1.sum==ni2.sum)
			return ni1.value>ni2.value;
		return ni1.sum>ni2.sum;
	}
};
int main(int argc, char* argv[])
{

	for (int n; cin>>n && n; )
	{
		vector<NumberInfo> vints;
		vints.reserve(n+1);
		for (NumberInfo num;n-- && cin>>num;)
		{
			vints.push_back(num);
		}
		sort(vints.begin(), vints.end(), compare);
		vector<NumberInfo>::iterator it=vints.begin();
		for (it=vints.begin(); it!=(vints.end()-1); ++it)
		{
			cout<<*it<<" ";
		}
	//	copy(vints.begin(), vints.end(), ostream_iterator<NumberInfo>(cout, " "));
		cout<<*it<<endl;
	}
	return 0;
}